package jp.co.mapion.conf;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

public final class Conf {

	private static final String DEFALUT_SEPARATOR = ", ";

	private static Properties properties;

	static {
		init();
	}

	private Conf() {
	}

	public static void init() {
		try {
			properties = new Properties();
			String confPath = "/" + ConfigFileReader.getConfig();
			InputStream conf = Conf.class.getResourceAsStream(confPath);
			if (conf != null) {
				properties.load(conf);
			}
			String localPath = "/" + ConfigFileReader.getHostsDir() + "/" +
				InetAddress.getLocalHost().getCanonicalHostName().toLowerCase() + ".properties";
			InputStream local = Conf.class.getResourceAsStream(localPath);
			if (local != null) {
				properties.load(local);
			}
			for (Map.Entry<Object, Object> e : System.getProperties().entrySet()) {
				properties.put(e.getKey(), e.getValue());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String get(String key) {
		return properties.getProperty(key);
	}

	public static String[] gets(String key) {
		return gets(key, DEFALUT_SEPARATOR);
	}

	public static String[] gets(String key, String separator) {
		List<String> entriesList = getList(key, separator);
		String[] entries = new String[entriesList.size()];
		entriesList.toArray(entries);
		return entries;
    }

	public static List<String> getList(String key) {
		return getList(key, DEFALUT_SEPARATOR);
	}

	public static List<String> getList(String key, String separator) {
		List<String> entriesList = new ArrayList<String>();
		String values = get(key);
		if (values != null) {
			StringTokenizer st = new StringTokenizer(values, separator);
			while (st.hasMoreTokens()) {
				String token = st.nextToken();
				entriesList.add(token);
			}
		}
		return entriesList;
	}

	public static int size() {
		return properties.size();
	}

	static Set<Object> keySet() {
		return properties.keySet();
	}

	static void put(String key, String value) {
		properties.put(key, value);
	}
}